package com.example.skinhelper;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;



public class SkinIns implements ISkin {
    private Application mApplication;
    private static SkinIns mSkinPeeler = null;
    //资源包Resources
    private Resources mResource;
    //资源包包名
    private String skinPackageName;
    //页面数据集合， 页面、页面中需要替换的view，切换监听，当页面销毁时自动销毁数据

    private List<ViewSetting> viewSettings=new ArrayList<>();

    private SkinViewManager skinViewManager=new SkinViewManager();

    public SkinIns() {
        viewSettings.add(new ColorViewSetting());
        viewSettings.add(new DrawViewSetting());
    }

    public SkinViewManager getSkinViewManager() {
        return skinViewManager;
    }

    public static SkinIns getInstance() {
        if (mSkinPeeler == null) {
            synchronized (SkinIns.class) {
                if (mSkinPeeler == null) {
                    mSkinPeeler = new SkinIns();
                }
            }
        }
        return mSkinPeeler;
    }

    public void init(Application mApplication) {
        this.mApplication = mApplication;
        //注册activity监听
        registerActivityLifecycleCallbacks(mApplication);

        //创建一个皮肤包Resources
        initResources(mApplication);
        //设置皮肤包包名
        initSkinPackageName(mApplication);
        IdUtils.load(mApplication);
    }

    public ViewSetting getMachViewSetting(String s){
        for (int i = 0; i < viewSettings.size(); i++) {
            if (inList(viewSettings.get(i).getAttrNameList(),s)){
                return viewSettings.get(i);
            }
        }
        return null;
    }

    public List<ViewSetting> getViewSettings(String s){
        List<ViewSetting> data=new ArrayList<>();
        for (int i = 0; i < viewSettings.size(); i++) {
            if (inList(viewSettings.get(i).getAttrNameList(),s)){
                data.add(viewSettings.get(i));
            }
        }
        return data;
    }

    public boolean inList(List<String> data,String s){
        for (int i = 0; i < data.size(); i++) {
            if (s.equals(data.get(i))){
                return true;
            }
        }
        return false;
    }

    private void registerActivityLifecycleCallbacks(Application mApplication) {
        mApplication.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
                LayoutInflater mLayoutInflater = activity.getLayoutInflater();
                LayoutInflaterHelper.setFactorySetFalse(mLayoutInflater);
                LayoutInflaterHelper.setFactory2(activity, mLayoutInflater);

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
//                skinViewManager.skinActivity(activity);
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                 skinViewManager.removeActivity(activity);
            }
        });

    }

    private void initSkinPackageName(Application mApplication) {
        try {
            //获取外部Apk（皮肤薄） 包名
            PackageManager packageManager = mApplication.getPackageManager();
            PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(skinPackPath(), PackageManager.GET_ACTIVITIES);
            this.skinPackageName = packageArchiveInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initResources(Application mApplication) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPathMethod.invoke(assetManager, skinPackPath());
            mResource = new Resources(assetManager, mApplication.getResources().getDisplayMetrics(), mApplication.getResources().getConfiguration());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取皮肤包路径
     */
    private String skinPackPath() {
        SharedPreferences sp = mApplication.getSharedPreferences("skin-peeler", Context.MODE_PRIVATE);
        return sp.getString("skin-path", "");
    }

    /**
     * 设置皮肤包路径
     */
    private void setSkinPackPath(String skinPath) {
        SharedPreferences sp = mApplication.getSharedPreferences("skin-peeler", Context.MODE_PRIVATE);
        sp.edit().putString("skin-path", skinPath).commit();
    }

    /**
     * 皮肤发生改变，在代码中设置皮肤包中的图片等操作
     */
    private void skinChanged() {

    }

    public void skin(String skinPath) {

        setSkinPackPath(skinPath);
        initResources(mApplication);
        initSkinPackageName(mApplication);
        refreshSkinAllActivity();
    }



    private void refreshSkin(Activity activity){
        skinViewManager.skinActivity(activity);
    }

    private void refreshSkinAllActivity(){
        skinViewManager.skinAllActivity();
    }

    @Override
    public void restore() {
        setSkinPackPath("");
        initResources(mApplication);
        initSkinPackageName(mApplication);
        refreshSkinAllActivity();
    }

    public void restoreAndRefresh(Activity activity){
        refreshSkin(activity);
    }


    @Override
    public Resources getSkinResources() {
        if (isApply()) return mApplication.getResources();
        return mResource;
    }

    @Override
    public String getSkinPackageName() {
        if (isApply()) return mApplication.getPackageName();
        return skinPackageName;
    }

    public boolean isApply() {
        return mResource == null || TextUtils.isEmpty(skinPackageName) || TextUtils.isEmpty(skinPackPath());
    }

}
